/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.yuecai.modules.security.service;


import com.yuecai.exception.BadRequestException;
import com.yuecai.exception.EntityNotFoundException;
import com.yuecai.modules.security.JwtUserDto;
import com.yuecai.modules.yc_user.domain.YcUser;
import com.yuecai.modules.yc_user.service.YcUserService;
import com.yuecai.modules.yc_user.service.dto.YcUserDto;
import com.yuecai.modules.yc_user.service.impl.YcUserServiceImpl;
import com.yuecai.modules.yc_user.service.mapstruct.YcUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.Instant;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final YcUserService ycUserService;
    private final YcUserMapper ycUserMapper;


    @SneakyThrows
    @Override
    public JwtUserDto loadUserByUsername(String phone) {
        YcUser user;
        try {
            user = ycUserService.findByName(phone);
        } catch (EntityNotFoundException e) {
            // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
            throw new UsernameNotFoundException("", e);
        }
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else {
            if (user.getState()==1) {
                throw new BadRequestException("删除");
            }else if (user.getState()==2) {
                throw new BadRequestException("冻结");
            }
            if (!YcUserServiceImpl.isMobileNO(phone)){
                //修改最后登录时间，不一定登录成功
                user.setLastLoginTime(Instant.now());
                ycUserService.update(user);
            }
            YcUserDto dto = ycUserMapper.toDto(user);
            return new JwtUserDto(dto,null);
        }
    }

}
